// ==UserScript==
// @name         TMVN League InOut
// @namespace    https://trophymanager.com
// @version      1
// @description  Trophymanager: top in - out and summary transfer of current season
// @match        https://trophymanager.com/league/*
// @grant        none
// @downloadURL https://gitee.com/trophymanagerCN/tmjs/raw/master/535588/TMVN%20League%20InOut.user.js
// @updateURL https://gitee.com/trophymanagerCN/tmjs/raw/master/535588/TMVN%20League%20InOut.meta.js
// ==/UserScript==

(function () {
    'use strict';

    /* ----------------------------------------------------------- *
     * 1. Xây URL lịch sử chuyển nhượng hiện tại
     * ----------------------------------------------------------- */
    function getLeagueInfo() {
        let country,
            division,
            group;
        if (window.feed_nat && window.feed_div && window.feed_gro) {
            country = String(feed_nat);
            division = String(feed_div);
            group = String(feed_gro);
        } else {
            const m = location.pathname.match(/\/league\/([^\/]+)\/(\d+)\/(\d+)/);
            if (m)
                [, country, division, group] = m;
        }
        const season = (window.SESSION && SESSION.season) ? SESSION.season : '';
        return {
            country,
            division,
            group,
            season
        };
    }

    const info = getLeagueInfo();
    const historyURL = `https://trophymanager.com/history/league/${info.country}/${info.division}/${info.group}/transfers/${info.season}/`;

    /* ----------------------------------------------------------- *
     * 2. Lấy & phân tích HTML
     * ----------------------------------------------------------- */
    fetch(historyURL, {
        credentials: 'include'
    })
        .then(r => r.text())
        .then(html => {
            const doc = new DOMParser().parseFromString(html, 'text/html');
            const tables = doc.querySelectorAll('.column2_a table.zebra');
            if (tables.length < 2)
                throw 'Không tìm đủ 2 bảng buy sell';

            const [inTable, outTable] = tables;

            const totals = {}; // { clubId: {name, bought, sold} }
            const inTransfers = []; // giao dịch mua
            const outTransfers = []; // giao dịch bán

            const accu = (table, field, arr) => {
                table.querySelectorAll('tbody > tr').forEach(tr => {
                    const playerA = tr.querySelector('td:first-child a[player_link]');
                    const clubA = tr.querySelector('td:nth-child(3) a[club_link]');
                    const priceTd = tr.querySelector('td.right');
                    if (!playerA || !clubA || !priceTd)
                        return;

                    const playerName = playerA.textContent.trim();
                    const playerId = playerA.getAttribute('player_link');
                    const clubName = clubA.textContent.trim();
                    const clubId = clubA.getAttribute('club_link');
                    const price = parseFloat(priceTd.textContent.replace(/,/g, '')) || 0;

                    // lưu cho top-10
                    arr.push({
                        playerName,
                        playerId,
                        clubName,
                        clubId,
                        price
                    });

                    // cộng dồn cho CLB
                    if (!totals[clubId])
                        totals[clubId] = {
                            name: clubName,
                            bought: 0,
                            sold: 0
                        };
                    totals[clubId][field] += price;
                });
            };

            accu(inTable, 'bought', inTransfers);
            accu(outTable, 'sold', outTransfers);

            /* --------------------------------------------------- *
             * 3.  Hiển thị giao diện
             * --------------------------------------------------- */
            renderUI(totals, inTransfers, outTransfers, info.season);

            /* ----------------- hàm dựng & gắn khối HTML -------- */
            function renderUI(totals, inArr, outArr, season) {
                /* Xác định cột phải – ưu tiên .column3_a (trang League),
                nếu không có thì .column3 (trang History)                */
                const $col = $('.column3_a').length ? $('.column3_a')
                    : $('.column3').length ? $('.column3')
                        : null;
                if (!$col)
                    return; // không tìm thấy nơi gắn – bỏ qua

                /* ---- 1. Tạo bảng tổng hợp theo CLB ---- */
                const fmt = n => n.toFixed(1).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                const clubs = Object.values(totals)
                    .sort((a, b) => (b.sold - b.bought) - (a.sold - a.bought));

                let tblClb = `<table>
        <tr><th>Club</th><th align="right">Buy</th>
            <th align="right">Sell</th><th align="right">Profit</th></tr>`;
                clubs.forEach((c, i) => {
                    const odd = i % 2 ? ' class="odd"' : '';
                    const bal = c.sold - c.bought;
                    tblClb += `<tr${odd}><td>${c.name}</td>
                   <td align="right">${fmt(c.bought)}</td>
                   <td align="right">${fmt(c.sold)}</td>
                   <td align="right">${fmt(bal)}</td></tr>`;
                });
                tblClb += '</table>';

                /* ---- 2. Top-10 IN / OUT ---- */
                const top10 = list => [...list].sort((a, b) => b.price - a.price).slice(0, 10);

                const buildPlayerTbl = (list, dirTxt) => {
                    let rows = `<table>
          <tr><th>Player</th><th>Club</th><th align="right">Price</th></tr>`;
                    top10(list).forEach((t, i) => {
                        const odd = i % 2 ? ' class="odd"' : '';
                        rows += `<tr${odd}>
              <td><a href="/players/${t.playerId}/">${t.playerName}</a></td>
              <td>${t.clubName}</td>
              <td align="right">${fmt(t.price)}</td></tr>`;
                    });
                    return rows + '</table>';
                };

                /* ---- 3. Gộp thành một khối “box” ---- */
                const boxHTML = `
    <div class="box">
      <div class="box_head"><h2 class="std">IN OUT</h2></div>
      <div class="box_body">
        <div class="box_shadow"></div>

        <h3>SUMMARY</h3>
        <div>${tblClb}</div>

        <h3>TOP IN</h3>
        <div>${buildPlayerTbl(inArr, 'Buyer')}</div>

        <h3>TOP OUT</h3>
        <div>${buildPlayerTbl(outArr, 'Seller')}</div>
      </div>
      <div class="box_footer"><div></div></div>
    </div>`;

                $col.append(boxHTML);
            }

        })
        .catch(err => console.error('[TMVN script] Lỗi:', err));
})();
